<template>
    <div>
        <div class="container" >
            <div class="form-box" style="width:100%" >
                <el-form ref="formRef" :rules="rules" :model="productForm" :label-width="formLabelWidth">
                    <el-header>
                        <el-button type="primary" @click="onSubmit" plain>保存</el-button>
                        <el-button type="success" @click="onReset" plain>重置数据</el-button>
                        <el-button @click="func_back" plain>返回</el-button>
                    </el-header>
                    <el-container style="width:100%;">
                        <el-main >
                            <el-row>
                            <el-divider content-position="left">商品分类信息</el-divider>
                            <el-col :span=24>
                                {{productForm.productClassifyName}}
                            </el-col>
                            </el-row>
                            <el-row>
                            <el-divider content-position="left">商品信息</el-divider>
                            <el-col :span=24>
                            <el-form-item label="所属品牌" prop="productBoardId">
                                <el-input v-model="productForm.productBoardId"  v-if="false"/>
                                <el-input v-model="productForm.productBoardName" placeholder="选择品牌" clearable readonly size="medium" style="width:350px" @click="func_loadvBoardsDict()"/>
                            </el-form-item></el-col>
                            <el-col :span=24><el-form-item label="ID" v-if="false">
                                <el-input v-model="productForm.id" placeholder="ID" clearable size="medium" style="width:350px"/>
                            </el-form-item></el-col>
                            <el-form-item label="商品货号（批号）" prop="productSno">
                                <el-input v-model="productForm.productSno" placeholder="商品货号（批号）" maxlength="30" clearable size="medium" show-word-limit style="width:350px"/>
                            </el-form-item>
                            <el-col :span=24>
                            <el-form-item label="商品名称" prop="productName">
                                <el-input v-model="productForm.productName" placeholder="商品名称" clearable size="medium" maxlength="20" show-word-limit style="width:350px"/>
                            </el-form-item></el-col>
                            <el-col :span=24>
                            <el-form-item label="是否包邮" prop="shipmentType">
                                <el-switch v-model="productForm.shipmentType" class="handle-switch mr40"
                                placeholder="是否包邮"
                                :active-value= "1" :inactive-value= "0"
                                active-color="#13ce66" inactive-color="#ff4949" />
                            </el-form-item></el-col>
                            <el-col :span=24>
                            <el-form-item label="邮费" prop="shipmentPrice">
                                <el-input v-model="productForm.shipmentPrice" placeholder="邮费" clearable size="medium" maxlength="10" show-word-limit style="width:350px" align="right" />
                            </el-form-item></el-col>
                            <el-form-item label="价格" prop="price">
                                <el-input v-model="productForm.price" placeholder="价格" clearable size="medium" style="width:350px" align="right" />
                            </el-form-item>
                            <el-form-item label="积分兑换值" prop="points">
                                <el-input v-model="productForm.points" placeholder="积分兑换值" clearable size="medium" style="width:350px" align="right" />
                            </el-form-item>
                            <el-col :span=24>
                            <el-form-item label="原地址" prop="shipmentProvince">
                                <el-input v-model="productForm.strShipmentProvince" readonly size="medium" style="width:350px"/><br/>
                            </el-form-item>
                            <el-form-item label="发货省份（变更地址）" prop="shipmentProvince">
                                <el-input v-model="productForm.shipmentProvince" placeholder="发货省份" clearable size="medium" style="width:350px" v-if="false"/>
                                <el-cascader v-model="provinceOptionVal"
                                @focus="func_loadShipmentProvinceOptions" @change="func_setShipmentProvince"
                                :options="shipmentProvinceOptions" :props="provinceOptionProps" placeholder="发货省份" clearable size="medium" style="width:350px" />
                            </el-form-item></el-col>
                            <el-col :span=24>
                            <el-form-item label="概要描述（100字以内）" prop="productDescribe">
                                <el-input type="textarea" style="width:550px" maxlength="110" show-word-limit
                                :autosize="{ minRows: 10, maxRows: 12}" v-model="productForm.productDescribe" placeholder="项目描述">
                                </el-input>
                            </el-form-item></el-col>
                            </el-row>
                            <el-divider content-position="left">商品图片</el-divider>
                            <el-row><el-col :span=24>
                            <el-form-item label="商品展示主图">
                                <el-upload class="masterImage-uploader"
                                action="http://127.0.0.1:4890/portal/admin/file/uploadImage"
                                :show-file-list="false"
                                :on-success="func_masterImageUploadSuccess"
                                :before-upload="func_beforeMasterImageUpload">
                                    <el-image v-if="masterImageUrl" :src="masterImageUrl" class="masterImage" fit="cover"/>
                                    <i v-else class="el-icon-plus masterImage-uploader-icon"></i>
                                </el-upload>
                                <el-input v-model="productForm.urlPic" placeholder="商品展示主图" v-if="false"/>
                            </el-form-item></el-col></el-row>
                            <!-- 多张展示图 -->
                            <el-row><el-col :span=24>
                            <el-form-item label="多张展示图">
                            <el-upload
                                action="http://127.0.0.1:4890/portal/admin/file/uploadImage"
                                list-type="picture-card"
                                :on-preview="func_handleContentPicPreview"
                                :on-remove="func_handleContentPicRemove"
                                :on-success="func_handleContentPicsSuccess"
                                :file-list="fileList"
                            >
                                <i class="el-icon-plus" ></i>
                                <template #tip>
                                    <div class="el-upload__tip">
                                        <li>1. 仅支持图片类型文件，包含 jpg/png 格式文件。</li>
                                        <li>2. 单个文件上传限定 4MB 以内。</li>
                                    </div>
                                </template>
                            </el-upload>
                            <el-dialog v-model="dialogImageVisible" title="图片预览" :width="dialogImageWidth" center>
                                <el-image w-full :src="dialogImageUrl" alt="图片预览" />
                                <div style="padding: 14px">
                                    <span>{{productForm.productDescribe}}</span>
                                    <div class="bottom">
                                    <time class="time">{{ productForm.createTime }}</time>
                                    </div>
                                </div>
                                <template #footer>
                                    <span class="dialog-footer"><el-button @click="dialogImageVisible = false" plain>关闭</el-button></span>
                                </template>
                            </el-dialog>
                            <el-input v-model="productForm.contentPics" placeholder="商品多张展示图" v-if="false"/>
                            </el-form-item></el-col></el-row>
                            <el-divider content-position="left">富文本编辑</el-divider>
                            <el-row><el-col :span=24>
                            <el-form-item><span> {{productForm.detailsContent}}</span></el-form-item>
                            <el-form-item label="商品介绍详情">
                                <el-input type="textarea" style="width:550px" maxlength="110" show-word-limit
                                :autosize="{ minRows: 10, maxRows: 12}" v-model="productForm.detailsContent" placeholder="商品介绍详情">
                                </el-input>
                            </el-form-item></el-col></el-row>
                        </el-main>
                    </el-container>
				</el-form>
            </div>
        </div>
        <el-dialog v-model="vBoardsVisible" append-to-body>
            <VBoards @boardsDictData="func_loadvBoardsDictData" />
        </el-dialog>
    </div>
</template>

<script>
import { ref, reactive, toRefs } from "vue";
import { useRouter, useRoute } from 'vue-router';
import { ElMessage, ElMessageBox } from "element-plus";
import { findProductInfoListById, saveProductInfo } from "../../../api/hairmanager/products";
import { loadProvTrees, } from "../../../api/dict";

import { NO_DATA_SELECT_ERROR, SUCCESS_ADDDATA_DIALOG_MESSAGE, SUCCESS_DELDATA_DIALOG_MESSAGE, SUCCESS_EDITDATA_DIALOG_MESSAGE, formLabelWidth, } from "../../../api/CommonErrorMessage.js";

import VBoards from "./components/boards.vue";
export default {
    name: "productDetail",
    components: {VBoards, },
    setup() {
        const router = useRouter();
		const route = useRoute();
        const formLabelWidth = ref("170px");
        const dialogImageUrl = ref("");
        const dialogImageVisible = ref(false);
        const dialogImageWidth = ref(0);
        const fileList = ref([]);
        let id = route.query.id;
        const func_onLoad = () => {
            if (id > 0 ){
                findProductInfoListById(id).then((res) => {
                    if(res.code != 200) {
                        if(res.type == 0) {
                            ElMessage.warning(res.data.msg);
                        } else {
                            ElMessage.error(res.data.msg);
                        }
                    } else {
                        // fileList.value = []
                        fileList.value = [];
                        Object.keys(res.data).forEach((item) => {
                            productForm[item] = res.data[item];
                        });
                        if(null != productForm['contentPicList'] && productForm['contentPicList'].length > 0){
                            productForm['contentPicList'].forEach((item,index) => {
                                fileList.value.push(
                                    { name: 'pic'+index+'.jpeg', url: item,}
                                )
                            });
                        }
                        masterImageUrl.value= productForm['urlPic'];
                        productForm['shipmentProvince'] = res.data['shipmentProvince'];
                        productForm['strShipmentProvince'] = res.data['strShipmentProvince'];
                        productForm['shipmentProvinces'] = res.data['shipmentProvinces'];
                        provinceOptionVal.value = res.data['shipmentProvinces'];
                    }
                });
            }
        };
        func_onLoad();
        let productForm = reactive({
            id: 0,
            productSno: "",
            productName: "",
            productDescribe: "",
			points: 0,
			price: 0,
            urlPic: "",
			contentPics: "",
            shipmentType: 0,
            shipmentPrice: 0,
            shipmentProvince: "",
            strShipmentProvince: "",
			detailsContent: "",
            contentPicList: [],
            productClassifyId: 0,
			productBoardId: 0,
			productBoardName: "",
            createTime:"" ,
        });
        const rules = {
            productName: [
                { required: true, message: "请输入商品名称", trigger: "blur" },
            ],
            shipmentPrice : [
                { required: true, message: "请输入邮费", trigger: "blur" },
            ],
        };
        const formRef = ref(null);
        // =========================================================================================
        const provinceOptionVal = ref('');
		const shipmentProvinceOptions = ref([]);
        const provinceOptionProps = {
            checkStrictly: true,
        }
		const func_loadShipmentProvinceOptions = () => {
			loadProvTrees().then((res) => {
				shipmentProvinceOptions.value = res.data;
			});
		};
		const func_setShipmentProvince = () => {
			productForm.shipmentProvince = provinceOptionVal.value.join(',');
		};
        // 主业务处理 ========================================================================================= START
        // 提交
        const onSubmit = () => {
            let strPics = '';
            contentPicList.value.forEach((item) => {
                strPics = strPics + item.value +",";
            });
            productForm['contentPics'] = strPics;
            // 表单校验
            formRef.value.validate((valid) => {
                if (valid) {
                    saveProductInfo(productForm).then((res) => {
                        if(res.code != 200) {
                            if(res.type == 0) {
                                ElMessage.warning(res.data.msg);
                            } else {
                                ElMessage.error(res.data.msg);
                            }
                        } else {
                            ElMessage.success(SUCCESS_ADDDATA_DIALOG_MESSAGE);
                            router.push("/products");
                        }
                    });
                } else {
                    return false;
                }
            });
        };
        // 重置
        const onReset = () => {
            formRef.value.resetFields();
        };
        const func_back = () => {
            router.push("/products");
        }
        // 主图上传 ========================================================================================= START
        let masterImageUrl = ref('');
        const func_masterImageUploadSuccess = (res, file) => {
            if(file.response.code != 200) {
                if(res.type == 0) {
                    ElMessage.warning(res.data.msg);
                } else {
                    ElMessage.error(res.data.msg);
                }
            } else {
                var uploadFile = URL.createObjectURL(file.raw);
                productForm['urlPic'] = file.response.data.imgUrl;
                ElMessage.success("上传成功");
            }
        };
        const func_beforeMasterImageUpload = (file) => {
            const isJPG = file.type === 'image/jpeg';
            const isLt10M = file.size / 1024 / 1024 < 10;
            if (!isJPG) {
                ElMessage.warning('上传图片只能是 JPG 格式!');
            };
            if (!isLt10M) {
                ElMessage.warning('上传图片大小不能超过 10MB!');
            }
            return isJPG && isLt10M;
        };
        // 主图上传 ========================================================================================= END
        // 多图上传 ========================================================================================= START
        let contentPicList = ref([]);
        const func_handleContentPicsSuccess = (res, file) => {
            if(file.response.code != 200) {
                if(res.type == 0) {
                    ElMessage.warning(res.data.msg);
                } else {
                    ElMessage.error(res.data.msg);
                }
            } else {
                var uploadFile = URL.createObjectURL(file.raw);
                var imageUrl = file.response.data.imgUrl;
                contentPicList.value.push(imageUrl);
                productForm['contentPicList'] = contentPicList.value;
                ElMessage.success("上传成功");
            }
        }
        const func_handleContentPicPreview = (file) => {
            dialogImageUrl.value= file['url'];
            dialogImageVisible.value = true;
        }
        const func_handleContentPicRemove = (uploadFile, uploadFiles) => {
            console.log(uploadFile, uploadFiles);
        }
        // 多图上传 ========================================================================================= END
		// 品牌业务插件处理 ========================================================================================= START
		const vBoardsVisible = ref(false);
		const func_loadvBoardsDict = () => {
			vBoardsVisible.value = true;
		};
		const func_loadvBoardsDictData = (v) => {
			productForm['productBoardId'] = v['dicCode'];
			productForm['productBoardName'] = v['dicName'];
			vBoardsVisible.value = false;
		};
		// 品牌业务插件处理 ========================================================================================= END
        // =========================================================================================================
        return {
            // 系统环境变量
            formLabelWidth, rules, formRef, productForm, dialogImageVisible, dialogImageWidth, dialogImageUrl, fileList,
            shipmentProvinceOptions, provinceOptionProps, provinceOptionVal,
            // 主业务表单处理
            func_onLoad, onSubmit, onReset, func_back, func_loadShipmentProvinceOptions, func_setShipmentProvince,
            // 图片文件处理
            masterImageUrl, func_masterImageUploadSuccess, func_beforeMasterImageUpload,
            // 多图文件处理
            contentPicList, func_handleContentPicsSuccess, func_handleContentPicPreview, func_handleContentPicRemove,
            // 品牌业务插件处理
			vBoardsVisible, func_loadvBoardsDict, func_loadvBoardsDictData,
        };
    },
};
</script>
<style scoped>
.handle-box {
    margin-bottom: 20px;
}

.handle-select {
    width: 120px;
}

.handle-input {
    width: 300px;
    display: inline-block;
}
.table {
    width: 100%;
    font-size: 14px;
}
.red {
    color: #ff0000;
}
.mr10 {
    margin-right: 10px;
}
.table-td-thumb {
    display: block;
    margin: auto;
    width: 40px;
    height: 40px;
}
.el-row {
    margin-bottom: 20px;
}
.el-row:last-child {
    margin-bottom: 0;
}
.el-col {
    border-radius: 4px;
}
.grid-label {
    background: #00000;
    min-height: 36px;
    padding-left: 25px;
}
.grid-content {
    background: #00000;
    min-height: 36px;
    padding-left: 6px;
}
.row-bg {
    padding: 0px 0px 0px 0px;
}
.drawer-box-card {
    width:95%;
    margin-left:15px;
    overflow: auto;
}
.drawer-box-tabs {
    width:95%;
    margin-top:10px;
    margin-left:15px;
    overflow: auto;
    height: 900px;
}
.masterImage-uploader .masterImage {
  width: 100%;
  height: 100%;
  display: block;
  padding: 15px 15px 15px 15px
}
.masterImage-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}
.masterImage-uploader .el-upload:hover {
    border-color: #409EFF;
}
.masterImage-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}
.masterImage {
    width: 100%;
    height: 100%;
    display: block;
    align: center;
}
</style>